<template>
  <div>
    <el-steps :active="active" finish-status="success">
      <el-step title="填写商品信息"></el-step>
      <el-step title="填写商品促销"></el-step>
      <el-step title="填写商品属性"></el-step>
      <el-step title="选择商品关联"></el-step>
    </el-steps>



    <el-form ref="form" :model="productDTO" label-width="80px">
       <span v-show="active===1">
         <el-form-item label="商品分类">
            <dev class="block">
                <sapn class="demonstration"></sapn>
                <el-cascader
                  v-model="productDTO.productCategoryId"
                  :options="category"
                  :props=Cascader
                  @change="handleCascaderChange">
                </el-cascader>
            </dev>
         </el-form-item>
         <el-form-item label="商品名称">
            <el-input v-model="productDTO.name" style="width: 600px"></el-input>
          </el-form-item>
         <el-form-item label="副标题">
            <el-input v-model="productDTO.subTitle" style="width: 600px"></el-input>
          </el-form-item>
         <el-form-item label="商品品牌">
            <el-select v-model="productDTO.brandId">
              <el-option v-for="i in brandVo" :key="i.id" :label="i.name" :value="i.id"></el-option>
            </el-select>
          </el-form-item>
         <el-form-item label="商品介绍">
            <el-input type="textarea" v-model="productDTO.description" style="width: 600px"></el-input>
          </el-form-item>
         <el-form-item label="商品货号">
            <el-input v-model="productDTO.productSn" style="width: 600px"></el-input>
          </el-form-item>
         <el-form-item label="商品售价">
            <el-input v-model="productDTO.price" style="width: 600px"></el-input>
          </el-form-item>
         <el-form-item label="市场价">
            <el-input v-model="productDTO.originalPrice" style="width: 600px"></el-input>
          </el-form-item>
         <el-form-item label="商品库存">
            <el-input v-model="productDTO.stock" style="width: 600px"></el-input>
          </el-form-item>
         <el-form-item label="计量单位">
            <el-input v-model="productDTO.unit" style="width: 600px"></el-input>
          </el-form-item>
         <el-form-item label="商品重量">
            <el-input v-model="productDTO.weight" style="width: 400px"></el-input>克
          </el-form-item>
         <el-form-item label="排序">
            <el-input v-model="productDTO.sort" style="width: 600px"></el-input>
          </el-form-item>
       </span>

      <span v-show="active===2">
          <el-form-item label="赠送积分">
            <el-input v-model="productDTO.giftPoint" style="width: 600px"></el-input>
          </el-form-item>
         <el-form-item label="赠送成长值">
            <el-input v-model="productDTO.giftGrowth" style="width: 600px"></el-input>
          </el-form-item>
         <el-form-item label="积分购买限制">
            <el-input v-model="productDTO.usePointLimit" style="width: 600px"></el-input>
          </el-form-item>
         <el-form-item label="预告商品">
           <el-switch
             v-model="productDTO.previewStatus"
             :active-value=1
             :inactive-value=0
             active-color="#13ce66"
             inactive-color="#ff4949">
           </el-switch>
         </el-form-item>
         <el-form-item label="商品上架">
            <el-switch
              v-model="productDTO.publishStatus"
              :active-value=1
              :inactive-value=0
              active-color="#13ce66"
              inactive-color="#ff4949">
             </el-switch>
         </el-form-item>
         <el-form-item label="商品推荐">
            新品<el-switch
           v-model="productDTO.newStatus"
           :active-value=1
           :inactive-value=0
           active-color="#13ce66"
           inactive-color="#ff4949">
            </el-switch>
            推荐<el-switch
           v-model="productDTO.recommandStatus"
           :active-value=1
           :inactive-value=0
           active-color="#13ce66"
           inactive-color="#ff4949">
           </el-switch>
         </el-form-item>
         <el-form-item label="服务保证">
          <el-checkbox-group v-model="selectedServices">
            <el-checkbox :label="item" v-for="item in baozheng" :key="item">{{ item }}</el-checkbox>
          </el-checkbox-group>
         </el-form-item>
         <el-form-item label="详细页标题">
            <el-input v-model="productDTO.detailTitle" style="width: 600px"></el-input>
          </el-form-item>
         <el-form-item label="详细页描述">
            <el-input v-model="productDTO.detailDesc" style="width: 600px"></el-input>
          </el-form-item>
         <el-form-item label="商品关键字">
            <el-input v-model="productDTO.keywords" style="width: 600px"></el-input>
          </el-form-item>
         <el-form-item label="商品备注">
            <el-input v-model="productDTO.note" style="width: 400px"></el-input>
          </el-form-item>
         <el-form-item label="选择优惠方式">
            <el-radio-group v-model="productDTO.promotionType" size="small">
              <el-radio-button :label="0">无优惠</el-radio-button>
              <el-radio-button :label="1">特惠促销</el-radio-button>
              <el-radio-button :label="2">会员价格</el-radio-button>
              <el-radio-button :label="3">阶梯价格</el-radio-button>
              <el-radio-button :label="4">满减价格</el-radio-button>
            </el-radio-group>
         </el-form-item>
         <el-form-item v-show="productDTO.promotionType===1">
            <div>
              开始时间：
              <el-date-picker
                v-model="productDTO.promotionStartTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                :picker-options="pickerOptions1"
                placeholder="选择开始时间">
              </el-date-picker>
            </div>
            <div class="littleMargin">
              结束时间：
              <el-date-picker
                v-model="productDTO.promotionEndTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                :picker-options="pickerOptions1"
                placeholder="选择结束时间">
              </el-date-picker>
            </div>
            <div class="littleMargin">
              促销价格：
              <el-input style="width: 220px" v-model="productDTO.promotionPrice" placeholder="输入促销价格"></el-input>
            </div>
         </el-form-item>


         <el-form-item v-show="productDTO.promotionType===2">
           <div v-for="(item, index) in productDTO.memberPriceList" :class="{littleMargin:index!==0}">
             {{item.memberLevelName}}：
             <el-input v-model="item.memberPrice" style="width: 200px"></el-input>
           </div>
         </el-form-item>

         <el-form-item v-show="productDTO.promotionType===3">
            <el-table :data="productDTO.productLadderList"
                      style="width: 80%" border>
              <el-table-column
                label="数量"
                align="center"
                width="120">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.count"></el-input>
                </template>
              </el-table-column>
              <el-table-column
                label="折扣"
                align="center"
                width="120">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.discount"></el-input>
                </template>
              </el-table-column>
              <el-table-column
                label="折后价格"
                align="center"
                width="120">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.price"></el-input>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="操作">
                <template slot-scope="scope">
                  <el-button type="text" @click="handleRemoveProductLadder(scope.$index, scope.row)">删除</el-button>
                  <el-button type="text" @click="handleAddProductLadder(scope.$index, scope.row)">添加</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>

         <el-form-item v-show="productDTO.promotionType===4">
          <el-table :data="productDTO.productFullReductionList" style="width: 80%" border>
            <el-table-column
              label="满"
              align="center"
              width="120">
              <template slot-scope="scope">
                <el-input v-model="scope.row.fullPrice"></el-input>
              </template>
            </el-table-column>
            <el-table-column
              label="立减"
              align="center"
              width="120">
              <template slot-scope="scope">
                <el-input v-model="scope.row.reducePrice"></el-input>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="操作">
              <template slot-scope="scope">
                <el-button type="text" @click="handleRemoveFullReduction(scope.$index, scope.row)">删除</el-button>
                <el-button type="text" @click="handleAddFullReduction(scope.$index, scope.row)">添加</el-button>
              </template>
            </el-table-column>
           </el-table>
         </el-form-item>
       </span>

      <span v-show="active===3">
          <el-form-item label="商品类型">
            <el-select v-model="productDTO.productAttributeCategoryId" @change="getValueByid(productDTO.productAttributeCategoryId)">
              <el-option v-for="i in productAttributeCategoryVO" :key="i.id" :label="i.name" :value="i.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="active === 3" label="商品规格">
              <el-card class="box-card">
                  <div v-for="i in productCategoryVo" :key="i.id" class="text item">
                      {{ i.categoryName }}
                    <div style="margin: 15px 0;"></div>
                    <el-checkbox-group v-model="checkAttrs" @change="changcheckAttrs">
                       <el-checkbox v-for="value in i.objectList" :label="value" :key="value.cid">
                        {{ value.attrName }}
                      </el-checkbox>
                    </el-checkbox-group>
                  </div>
              </el-card>
           <el-table :data="productDTO.productSkuStock" border style="width: 100%;margin-top: 30px">
            <el-table-column v-for="(item,index) in productCategoryVo" :key="index"
                             :prop="item.id+''"
                             :label="item.categoryName"
                             width="180">
            </el-table-column>
            <el-table-column
              prop="date"
              label="销售价格"
              width="180">
              <template slot-scope="scope">
                <el-input v-model="scope.row.price" placeholder="请输入内容">
                   <template slot="append">元</template>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column
              prop="name"
              label="促销价格"
              width="180">
              <template slot-scope="scope">
                <el-input v-model="scope.row.promotionPrice">
                   <template slot="append">元</template>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column
              prop="address"
              label="商品库存">
              <template slot-scope="scope">
                <el-input v-model="scope.row.stock">
                   <template slot="append"></template>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column
              prop="address"
              label="库存预警值">
              <template slot-scope="scope">
                <el-input v-model="scope.row.lowStock">
                   <template slot="append"></template>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column
              prop="address"
              label="SKU编号">
              <template slot-scope="scope">
                <el-input v-model="scope.row.productSn">
                   <template slot="append"></template>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column prop="address" label="多图片">
                <el-upload
                  class="upload-demo"
                  action="/dev-api/file/upload"
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                  :on-success="handleSuccess"
                  list-type="picture">
                  <el-button size="small" type="primary">点击上传</el-button>
                  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                </el-upload>
            </el-table-column>
             <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  @click="test(scope.row)">编辑</el-button>
              </template>
            </el-table-column>
           </el-table>
           <el-button style="margin-top: 15px" type="primary" @click="loadSKU">刷新列表</el-button>
           <el-button style="margin-top: 15px" type="primary">同步价格</el-button>
           <el-button style="margin-top: 15px" type="primary">同步库存</el-button>
          </el-form-item>
          <el-form-item label="商品参数">
            <el-card class="box-card">
                <div v-for="i in productCategoryVo2" :key="i.id" class="text item">
                      {{ i.categoryName }}：
                    <el-select v-model="productDTO.arrtList">
                      <el-option v-for="value in i.objectList" :label="value.attrName" :key="value.cid">
                      </el-option>
                    </el-select>
                  </div>
            </el-card>
          </el-form-item>
          <el-form-item label="商品相册">
            <el-upload
              action="/dev-api/file/upload"
              list-type="picture-card"
              :on-preview="handlePreview1"
              :on-remove="handleRemove1"
              :on-success="handleSuccess1">
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
          <img v-for="i in productDTO.imgUrl" :src="i" alt="图片损坏">
          <el-form-item label="商品详情">
            <!-- 富文本编辑器容器 -->
            <div ref="editor"></div>
          </el-form-item>
        </span>

      <span v-show="active===4">
          <el-form-item label="商品类型">
            <el-select v-model="productDTO.productAttributeCategoryId" @change="getValueByid(productDTO.productAttributeCategoryId)">
              <el-option v-for="i in productAttributeCategoryVO" :key="i.id" :label="i.name" :value="i.id"></el-option>
            </el-select>
          </el-form-item>
      </span>
    </el-form>



    <el-button type="primary" @click="finish" v-show="active===4">完成商品编辑</el-button>
    <el-button v-if="active < 4"  type="primary" style="margin-top: 12px" @click="next">下一步</el-button>
    <el-button v-if="active > 1"  type="primary" style="margin-top: 12px" @click="pre">上一步</el-button>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）,
//例如：import 《组件名称》 from '《组件路径》,

import Quill from 'quill'
import {getValueByid, saveProductAttributeCategory} from "@/api/product/productAttributeCategory";
import {findALlBrand} from "@/api/product/brand";
import {findAllproductAttributeCategoryName} from "@/api/product/productAttribute";
import {Cascader} from "element-ui";
import {recursion, update} from "@/api/product/product";

export default {
  //import引入的组件需要注入到对象中才能使用"
  components: {Quill},
  props: {},
  data() {
    //这里存放数据"

    return {
      //级联定义
      category:[],
      Cascader:{expandTrigger:'hover',value:'id',label:'name',children:'chilren'},
      checkAttrs:[],
      active: 1,
      productDTO:{
        productSkuStock:[
          {
            pics:{}
          }
        ],
        arrtList:[],
        serviceIds:'',
        imgUrl:[]
      },
      productAttributeCategoryVO:{},
      productCategoryVo:{},
      productCategoryVo2:{},
      brandVo:{},
      baozheng:["无忧退货","快速退款","免费包邮"]
    };
  },
  //计算属性 类似于data概念",
  computed: {
    Cascader() {
      return Cascader
    },
    selectedServices: {
      get() {
        return this.productDTO.serviceIds.split(',').filter(Boolean);
      },
      set(value) {
        this.productDTO.serviceIds = value.join(',');
      }
    }
  },
  //监控data中的数据变化",
  watch: {
    selectedServices: {
      handler(val) {
        this.selectedServices = val; // 确保selectedServices不变
      },
      deep: true
    }
  },
  //方法集合",
  methods: {
    handleCascaderChange(value) {
      // 将多级联动数据数组的最后一个值赋给 v-model
      this.productDTO.productCategoryId = value[value.length - 1];
    },
    //级联
    recursion(){
      recursion(0).then(
        res=>{
          this.category=res.data
        }
      )
    },
    test(va){
      alert(JSON.stringify(va))
      console.log(this.productDTO.productSkuStock.pics)
    },
    //刷新sku列表
    loadSKU(){
      alert(JSON.stringify(this.checkAttrs))
      saveProductAttributeCategory(this.checkAttrs).then(
        res=>{
          this.productDTO.productSkuStock=res.data
        }
      )
    },
    changcheckAttrs(val){

    },
    getValueByid(id){
      getValueByid(id,0).then(
        res=>{
          console.log(res)
          this.productCategoryVo=res.data
        }
      )
      getValueByid(id,1).then(
        res=>{
          console.log(res)
          this.productCategoryVo2=res.data
        }
      )

    },
    findBrandListDong(){
      findALlBrand().then(
        res=>{
          this.brandVo=res.data
        }
      )
    },
    findDongProductAttributeCategory(){
      findAllproductAttributeCategoryName().then(
        res=>{
          console.log(res)
          this.productAttributeCategoryVO=res.data
        }
      )
    },
    onSubmit1(){

    },
    handlePreview(file){

    },
    handleRemove(file) {
      this.productDTO.productSkuStock.pics=file.url
    },
    handleSuccess(response,file,fileList){
      console.log(response)
      this.productDTO.productSkuStock.pics=[]
      for (let fileListKey in fileList) {
        this.productDTO.productSkuStock.pics.push(fileList[fileListKey].response.data.url)
      }
    },
    handlePreview1(file){

    },
    handleRemove1(file) {
      this.productDTO.imgUrl=file.url
    },
    handleSuccess1(response,file,fileList){
      console.log(response)
      this.productDTO.imgUrl=[]
      for (let fileListKey in fileList) {
        this.productDTO.imgUrl.push(fileList[fileListKey].response.data.url)
      }
    },
    // 步骤条下一步的方法
    next() {
      if (this.active++ > 3) this.active = 1
    },
    // 步骤条上一步的方法
    pre() {
      if (this.active-- < 2) this.active = 1
    },
    finish(){
      update(this.productDTO).then(
        res=>{
          this.$message.success("修改成功")
          this.$router.push({path:'/product/product'})
        }
      )
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）",
  created() {
    this.productDTO=this.$route.query.val
    this.recursion()
    this.findBrandListDong()
    this.findDongProductAttributeCategory()
  },
  //生命周期 - 挂载完成（可以访问DOM元素）",
  mounted() {
    this.editor = new Quill(this.$refs.editor, {
      modules: {
        // 配置富文本编辑器的模块
        toolbar: {
          container: [
            ['bold', 'italic', 'underline', 'strike'],
            ['custom-button'],
            ['image', 'link'],
            [{'list': 'ordered'}, {'list': 'bullet'}],
            ['clean'],
          ],
          handlers: {
            'custom-button': function () {
              const currentDate = new Date().toLocaleDateString()
              this.quill.insertText(this.quill.getLength(), currentDate)
            }
          }
        }
      },

      // 富文本编辑器的配置
      placeholder: '请输入内容',
      theme: 'snow',

    }),
      this.editor.on('text-change',()=>{
        this.productDTO.detailHtml=this.editor.root.innerHTML
      })
  },
  beforeCreate() {

  }, //生命周期 - 创建之前",
  beforeMount() {
  }, //生命周期 - 挂载之前",
  beforeUpdate() {
  }, //生命周期 - 更新之前",
  updated() {
  }, //生命周期 - 更新之后",
  beforeDestroy() {
  }, //生命周期 - 销毁之前",
  destroyed() {
  }, //生命周期 - 销毁完成",
  activated() {
  } //如果页面有keep-alive缓存功能，这个函数会触发",
};
</script>
<style scoped>

</style>
